import { useState, useEffect } from "react";
import { Table, Select, DatePicker, Button, Row, Col, message, Space, Pagination } from "antd";
import type { TableProps } from "antd";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import { t } from "@/locales/i18n";
import alarmService from "@/api/alarm/alarm";
import deviceService from "@/api/device/device";
import areaService from "@/api/device/area";
import type { AreaSelect, SectionSelect, AlarmHistoryItem } from "#/alarm";
import '../style/index.css';

const { RangePicker } = DatePicker;

interface QueryParams {
  pageNo: number;
  pageSize: number;
  areaId: string | undefined;
  sectionId: string | undefined;
  totalCount: number;
}

function HistoryAnalysis() {
  const [listQuery, setListQuery] = useState<QueryParams>({
    pageNo: 1,
    pageSize: 10,
    areaId: undefined,
    sectionId: undefined,
    totalCount: 0
  });

  const [dateValue, setDateValue] = useState<[Dayjs, Dayjs]>([
    dayjs().startOf('day'),
    dayjs()
  ]);
  const [loading, setLoading] = useState(false);
  const [tableData, setTableData] = useState<AlarmHistoryItem[]>([]);
  const [areaList, setAreaList] = useState<AreaSelect[]>([]);
  const [secList, setSecList] = useState<SectionSelect[]>([]);

  // 日期快捷选项
  const dateShortcuts = {
    items: [
      {
        label: '最近一周',
        value: [dayjs().subtract(7, 'day'), dayjs()]
      },
      {
        label: '最近一个月',
        value: [dayjs().subtract(30, 'day'), dayjs()]
      },
      {
        label: '最近三个月',
        value: [dayjs().subtract(90, 'day'), dayjs()]
      }
    ]
  };

  useEffect(() => {
    getAreaList();
  }, []);

  const getAreaList = async () => {
    try {
      const response = await areaService.getAreaList({});
      if (response?.data) {
        const areaData = response.data.map(item => ({
          value: item.areaId,
          label: item.areaName
        }));
        setAreaList(areaData);
        if (response.data.length > 0) {
          setListQuery(prev => ({ ...prev, areaId: response.data[0].areaId }));
          getSectionList(response.data[0].areaId);
        }
      }
    } catch (err) {
      console.error('Error fetching area list:', err);
    }
  };

  const getSectionList = async (areaId: string) => {
    try {
      const response = await deviceService.getDeviceList({ areaId });
      if (response?.data) {
        const sectionData = response.data.map(item => ({
          value: item.sectionId,
          label: item.sectionName
        }));
        setSecList(sectionData);
        if (response.data.length > 0) {
          setListQuery(prev => ({ ...prev, sectionId: response.data[0].sectionId }));
          getDbRecordList(1, listQuery.pageSize, response.data[0].sectionId);
        }
      }
    } catch (err) {
      console.error('Error fetching section list:', err);
    }
  };

  const getDbRecordList = async (page: number = 1, pageSize: number = 10, sectionId?: string) => {
    if (!checkQuery()) return;

    try {
      setLoading(true);
      const response = await alarmService.historyCustomAlarmPage({
        beginDate: dateValue[0].format('YYYY-MM-DD HH:mm:ss'),
        endDate: dateValue[1].format('YYYY-MM-DD HH:mm:ss'),
        areaId: listQuery.areaId,
        sectionId: sectionId || listQuery.sectionId,
        pageSize,
        pageNo: page
      });

      if (response?.data) {
        setTableData(response.data.list);
        setListQuery(prev => ({
          ...prev,
          totalCount: response.data.count,
          pageNo: response.data.num
        }));
      }
    } catch (err) {
      console.error('Error fetching alarm history:', err);
    } finally {
      setLoading(false);
    }
  };

  const checkQuery = () => {
    if (!dateValue) {
      message.warning('请选择日期');
      return false;
    }
    if (!listQuery.areaId || !listQuery.sectionId) {
      message.warning('请选择区域和断面');
      return false;
    }
    return true;
  };

  const handleAreaChange = (value: string) => {
    setListQuery(prev => ({ ...prev, areaId: value, sectionId: undefined }));
    setSecList([]);
    getSectionList(value);
  };

  const handleExport = async () => {
    if (!checkQuery()) return;

    try {
      setLoading(true);
      const response = await alarmService.downLoadCustomAlarm({
        beginDate: dateValue[0].format('YYYY-MM-DD HH:mm:ss'),
        endDate: dateValue[1].format('YYYY-MM-DD HH:mm:ss'),
        areaId: listQuery.areaId,
        sectionId: listQuery.sectionId
      });

      if (response) {
        // 创建 blob 对象
        const blob = new Blob([response], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        });

        // 创建下载链接并自动下载
        const link = document.createElement('a');
        const url = window.URL.createObjectURL(blob);
        link.href = url;
        link.download = `历史数据_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`;
        document.body.appendChild(link);
        link.click();

        // 清理
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
      } else {
        message.warning('暂无数据');
      }
    } catch (err) {
      console.error('Error exporting data:', err);
    } finally {
      setLoading(false);
    }
  };

  const columns: TableProps<AlarmHistoryItem>['columns'] = [
    {
      title: '开始时间',
      dataIndex: 'alarmDate',
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '结束时间',
      dataIndex: 'endDate',
      render: (text) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
    },
    {
      title: '断面名称',
      dataIndex: 'sectionName'
    },
    {
      title: '类型',
      dataIndex: 'typeName'
    },
    {
      title: '内容',
      dataIndex: 'alarmReason'
    }
  ];

  return (
    <div className="p-6 flex flex-col h-full">
      <div className="mb-4 flex-none">
        <Row gutter={[16, 16]} align="middle" wrap>
          <Col flex="320px">
            <div className="flex items-center">
              <label className="inline-block w-20 text-right mr-2">区域名称</label>
              <Select
                value={listQuery.areaId}
                placeholder="请选择区域名称"
                onChange={handleAreaChange}
                className="w-full"
                allowClear
                showSearch
                options={areaList}
                filterOption={(input, option) =>
                  (option?.label?.toString() ?? '').toLowerCase().includes(input.toLowerCase())
                }
              />
            </div>
          </Col>
          <Col flex="320px">
            <div className="flex items-center">
              <label className="inline-block w-20 text-right mr-2">断面名称</label>
              <Select
                value={listQuery.sectionId}
                placeholder="请选择断面名称"
                onChange={(value) => {
                  setListQuery(prev => ({ ...prev, sectionId: value }));
                  getDbRecordList(1, listQuery.pageSize, value);
                }}
                className="w-full"
                allowClear
                showSearch
                options={secList}
                filterOption={(input, option) =>
                  (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                }
              />
            </div>
          </Col>
          <Col flex="420px">
            <div className="flex items-center">
              <label className="inline-block w-20 text-right mr-2">时间范围</label>
              <RangePicker
                showTime
                value={dateValue}
                onChange={(dates) => setDateValue(dates as [Dayjs, Dayjs])}
                className="w-full"
                presets={dateShortcuts.items}
              />
            </div>
          </Col>
          <Col flex="auto" className="text-right">
            <Space>
              <Button type="primary" onClick={() => getDbRecordList()}>
                查询
              </Button>
              <Button 
                onClick={handleExport} 
                loading={loading}
              >
                导出
              </Button>
            </Space>
          </Col>
        </Row>
      </div>

      <div className="flex-1 overflow-hidden relative">
        <Table
          columns={columns}
          dataSource={tableData}
          loading={loading}
          pagination={false}
          scroll={{ 
            x: true,
            y: 'calc(100vh - 310px)'
          }}
          className="custom-table"
          size="small"
          bordered
        />
        
        <div className="absolute bottom-0 right-0 w-full py-3 px-6">
          <div className="flex justify-end">
            <Pagination
              total={listQuery.totalCount}
              size="small"
              current={listQuery.pageNo}
              pageSize={listQuery.pageSize}
              onChange={(page, pageSize) => getDbRecordList(page, pageSize)}
              showSizeChanger
              showQuickJumper
              showTotal={(total) => `共 ${total} 条`}
              pageSizeOptions={['10', '20', '30', '40', '50', '100']}
            />
          </div>
        </div>
      </div>
    </div>
  );
}

export default HistoryAnalysis;
